package com.cx.controller;

import com.cx.pojo.Users;
import com.cx.service.LoginService;
import com.cx.service.RegisterService;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("register")
public class RegisterController {
    @Autowired
    private RegisterService registerService;

    @Autowired
    private LoginService loginService;


    @GetMapping("/userRegister")
    public String reg(Model model) {

        return "login";
    }

    @RequestMapping("/userRegister")
    @ResponseBody
    public  String UserRegister(Users users , HttpServletRequest request, Model model){

        System.out.println(users.getUserName());
        if ((registerService.isExist(users.getUserName()))!=null) {
            return "login";
        }else if ((registerService.isExist(users.getUserName()))==null){
           registerService.insertUser(users);
            return "success";
        }



       return "success";
    }



    @RequestMapping("/userLogin")
    @ResponseBody
    public String UsersLogin(Users users ,HttpServletRequest request){
       Users userInfo= loginService.selectByNameAndPwd(users.getUserName(),users.getUserPassword());

       HttpSession session = request.getSession();
       if (userInfo != null){
           session.setAttribute("user",userInfo);
       } else{
           return "用户名或密码错误";
       }

        return "success";

    }
}
